package com.aryankh.interceptor;

import com.aryankh.configuration.CustomObjectMapper;
import com.aryankh.constant.Constants;
import com.aryankh.core.RedisTemplate;
import com.aryankh.entity.KhLoginUser;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Set;

/**
 * @version 1.0
 * @Author AryanKH
 * @Date 2022/5/29 13:19
 * @Default
 */
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private CustomObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        ResponseEntity<String> res = ResponseEntity.status(401).body("Bad Creadentials!");
//        //若不是白名单的请求,进行检测
//        String token = request.getHeader(Constants.AUTHORIZATION);
//        // String tokenKey=Constants.TOKEN_PREFIX+request.getHeader("username")+":"+token;
//        //先判断有无Authorization 拿到首部信息 Authorization 的值
//        if (token == null) {
//            response.setStatus(401);
//            response.getWriter().write(objectMapper.writeValueAsString(res));
//            return false;
//        }
//        Set<String> keys = redisTemplate.keys(Constants.TOKEN_PREFIX + "*" + token);
//        if (keys == null || keys.size() == 0) {
//            response.setStatus(401);
//            response.getWriter().write(objectMapper.writeValueAsString(res));
//            return false;
//        }
//        String tokenKey = (String) keys.toArray()[0];
//        //使用token去redis中查看有无对应的loginUser
//        KhLoginUser khLoginUser = redisTemplate.getObject(tokenKey, new TypeReference<>() {});
//
//        if (khLoginUser == null) {
//            response.setStatus(401);
//            response.getWriter().write(objectMapper.writeValueAsString(res));
//            return false;
//        }
//        //续命token的过去时间
//        redisTemplate.expire(tokenKey, Constants.TOKEN_TIME);

        return true;
    }
}
